<template>
  <div>
    <h1>My Public IP Address</h1>
    <p v-if="loading">Loading...</p>
    <p v-if="error" class="error">{{ error }}</p>
    <p v-if="ip">Your IP Address is: {{ ip }}</p>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue';
import axios from 'axios';

export default defineComponent({
  name: 'GetIpAddress',
  setup() {
    // 定义响应式变量
    const ip = ref<string | null>(null);
    const loading = ref<boolean>(true);
    const error = ref<string | null>(null);

    // 获取公网IP的函数
    const fetchIp = async () => {
      try {
        loading.value = true;  // 设置加载状态为 true
        error.value = null;    // 清除之前的错误

        // 发送请求到 ipify API 获取公网 IP
        const response = await axios.get('https://api.ipify.org?format=json');
        ip.value = response.data.ip;  // 将 IP 地址设置到变量中
        console.log(ip.value);
      } catch (err) {
        error.value = 'Unable to fetch IP address';  // 错误处理
      } finally {
        loading.value = false;  // 请求完成，加载状态为 false
      }
    };

    // 使用 onMounted 钩子在组件挂载时调用 fetchIp 函数
    onMounted(() => {
      fetchIp();
    });

    // 返回状态变量
    return {
      ip,
      loading,
      error
    };
  }
});
</script>

<style scoped>
.error {
  color: red;
}
</style>
